export default class Snake {
    head: HTMLElement
    bodies: HTMLCollection
    element: HTMLElement
    ischuan: boolean = true
    constructor() {
        this.element = document.getElementById('snk')
        this.head = document.querySelector('#snk>div')
        this.bodies = this.element.getElementsByTagName('div')
    }
    get X() {
        return this.head.offsetLeft
    }
    get Y() {
        return this.head.offsetTop
    }
    set X(v: number) {
        if (v == this.X) return
        if (this.ischuan) {
            if (v == -10) {
                v = 290
            } else if (v == 300) {
                v = 0
            }
        } else { if (v < 0 || v > 290) throw new Error('蛇撞墙了，GAME OVER!') }

        if (this.bodies[1] && (this.bodies[1] as HTMLElement).offsetLeft === v) {
            // console.log('水平方向发生了掉头');
            // 如果发生了掉头，让蛇向反方向继续移动
            if (v > this.X) {
                // 如果新值value大于旧值X，则说明蛇在向右走，此时发生掉头，应该使蛇继续向左走
                v = this.X - 10;
            } else {
                // 向左走
                v = this.X + 10;
            }
        }
        this.movebody()
        this.head.style.left = v + 'px'
        this.checkheadbody(this.X, this.Y)
    }
    set Y(v: number) {
        if (v == this.Y) return
        if (this.ischuan) {
            if (v == -10) {
                v = 290
            } else if (v == 300) {
                v = 0
            }
        } else { if (v < 0 || v > 290) throw new Error('蛇撞墙了，GAME OVER!') }
        // if(v<0||v>290)throw new Error('蛇撞墙了，GAME OVER!')
        // if (v == -10) {
        //     v = 290
        // } else if (v == 300) {
        //     v = 0
        // }
        if (this.bodies[1] && (this.bodies[1] as HTMLElement).offsetTop === v) {
            // console.log('水平方向发生了掉头');
            // 如果发生了掉头，让蛇向反方向继续移动
            if (v > this.Y) {
                // 如果新值value大于旧值X，则说明蛇在向右走，此时发生掉头，应该使蛇继续向左走
                v = this.Y - 10;
            } else {
                // 向左走
                v = this.Y + 10;
            }
        }
        this.movebody()
        this.head.style.top = v + 'px'
        this.checkheadbody(this.X, this.Y)
    }
    set changechuan(v:boolean) {
        this.ischuan = v
    }
    addBody() {
        this.element.insertAdjacentHTML('beforeend', '<div></div>')
    }
    movebody() {
        for (let i = this.bodies.length - 1; i > 0; i--) {
            let x = (this.bodies[i - 1] as HTMLElement).offsetLeft;
            let y = (this.bodies[i - 1] as HTMLElement).offsetTop;
            (this.bodies[i] as HTMLElement).style.left = x + 'px';
            (this.bodies[i] as HTMLElement).style.top = y + 'px'
        }
    }
    checkheadbody(x: number, y: number) {
        for (let i = 2; i < this.bodies.length; i++) {
            if (x == (this.bodies[i] as HTMLElement).offsetLeft && y == (this.bodies[i] as HTMLElement).offsetTop) {
                throw new Error('蛇撞到自己了，GAME OVER!')
            }
        }
    }
}